package top.dotgo.web.base.kit;

import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * 事务工具
 * 千万记得开始后要进行commit，出现异常时一定要 rollback 否则会造成数据库卡死
 *
 * @author jornl
 * @date 2020-03-13 01:38:48
 */
@Component
public class TransKit {

    private static final ThreadLocal<TransactionStatus> STATUS = new ThreadLocal<>();

    private static PlatformTransactionManager transactionManager;

    public TransKit(PlatformTransactionManager transactionManager) {
        TransKit.transactionManager = transactionManager;
    }

    /**
     * 开始事务
     */
    public static void begin() {
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        STATUS.set(transactionManager.getTransaction(definition));
    }

    /**
     * 提交事务
     */
    public static void commit() {
        transactionManager.commit(STATUS.get());
        STATUS.remove();
    }

    /**
     * 回滚事务
     */
    public static void rollback() {
        transactionManager.rollback(STATUS.get());
        STATUS.remove();
    }
}
